package com.github.jiangwangyang.a2a.server;

import com.fasterxml.jackson.core.JsonProcessingException;
import io.a2a.A2A;
import io.a2a.server.agentexecution.AgentExecutor;
import io.a2a.server.agentexecution.RequestContext;
import io.a2a.server.events.EventQueue;
import io.a2a.server.tasks.TaskUpdater;
import io.a2a.spec.*;
import io.a2a.util.Utils;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Produces;

import java.util.Collections;
import java.util.List;

@ApplicationScoped
public class AgentExecutorProducer {

    @Produces
    public AgentExecutor agentExecutor() {
        return new AgentExecutor() {
            @Override
            public void execute(RequestContext context, EventQueue eventQueue) throws JSONRPCError {
                try {
                    System.out.println(Utils.OBJECT_MAPPER.writeValueAsString(context.getMessage()));
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }

                Task task = context.getTask();
                if (task != null) {
                    eventQueue.enqueueEvent(A2A.toAgentMessage("重复Task"));
                    return;
                }

                TaskUpdater updater = new TaskUpdater(context, eventQueue);
                updater.submit();
                updater.startWork();
                for (int i = 0; i < 10; i++) {
                    eventQueue.enqueueEvent(new TaskStatusUpdateEvent(
                            context.getTaskId(),
                            new TaskStatus(TaskState.WORKING),
                            context.getContextId(),
                            false,
                            Collections.emptyMap()));
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                updater.addArtifact(List.of(new TextPart("成功", null)), null, null, null);
                updater.complete();
            }

            @Override
            public void cancel(RequestContext context, EventQueue eventQueue) throws JSONRPCError {
                final Task task = context.getTask();
                if (task.getStatus().state() == TaskState.CANCELED) {
                    throw new TaskNotCancelableError();
                }
                if (task.getStatus().state() == TaskState.COMPLETED) {
                    throw new TaskNotCancelableError();
                }
                final TaskUpdater updater = new TaskUpdater(context, eventQueue);
                updater.cancel();
            }
        };
    }
}
